<template>
  <div class="order-page">
    <el-breadcrumb separator="/" style="margin-bottom: 16px;">
      <el-breadcrumb-item to="/home">{{ $t('menu.home') }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t('order.title') }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="order-card">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          class="order-table"
          v-loading="loading"
        >
          <el-table-column
            prop="orderNo"
            :label="$t('order.orderNo')"
            width="200"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="name"
            :label="$t('order.productName')"
            min-width="180"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="price"
            :label="$t('order.totalAmount')"
            width="110"
            align="center"
          >
            <template #default="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            :label="$t('order.status')"
            width="150"
            align="center"
          >
            <template #default="scope">
              <el-tag
                :type="getStatusType(scope.row.status)"
                class="tag-custom"
              >
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            :label="$t('order.createTime')"
            width="180"
            align="center"
          ></el-table-column>
          <el-table-column
            :label="$t('order.action')"
            width="120"
            align="center"
          >
            <template #default="scope">
              <el-button
                v-if="scope.row.statusKey === 1"
                type="primary"
                size="small"
                @click="handlePay(scope.row)"
              >
                {{ $t('order.pay') }}
              </el-button>
              <el-button
                v-if="scope.row.statusKey === 2"
                type="warning"
                size="small"
                @click="handleRefund(scope.row)"
              >
                {{ $t('order.refund') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="order-pagination"
        ></el-pagination>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';
import orderApi from '@/api/order.js';

const { t } = useI18n();
const userStore = useUserStore();

// 订单管理页面响应式数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载订单数据
const loadOrderData = async () => {
  try {
    loading.value = true;
    // ✅ 修复：使用userStore获取当前真实用户
    const response = await orderApi.getOrderList(userStore.currentUsername, currentPage.value, pageSize.value);
    
    // axios拦截器已经处理了错误情况，这里直接使用成功的数据
    if (response && response.data && response.data.records) {
      // 转换后端数据格式为前端展示格式
      tableData.value = response.data.records.map(item => ({
        id: item.id,
        name: item.productName,
        price: item.totalAmount,
        status: getStatusText(item.status),
        statusKey: item.status,  // 保存原始状态值用于判断按钮显示
        orderNo: item.orderNo,
        createTime: item.createTime,
        payTime: item.payTime
      }));
      total.value = response.data.total;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('加载订单数据失败:', error);
    ElMessage.error(t('order.loadFailed'));
  } finally {
    loading.value = false;
  }
};

// 状态文本转换
const getStatusText = (status) => {
  const statusMap = {
    1: t('order.statusPending'),
    2: t('order.statusPaid'), 
    3: t('order.statusCancelled'),
    4: t('order.statusRefunded'),
    5: t('order.statusTimeout')
  };
  return statusMap[status] || t('order.statusUnknown');
};

// 状态标签类型（使用翻译后的key来匹配）
const getStatusType = (statusText) => {
  const typeMap = {
    [t('order.statusPending')]: 'warning',
    [t('order.statusPaid')]: 'success',
    [t('order.statusCancelled')]: 'info',
    [t('order.statusRefunded')]: 'danger',
    [t('order.statusTimeout')]: 'info'
  };
  return typeMap[statusText] || 'info';
};

// 支付订单
const handlePay = async (row) => {
  try {
    const response = await orderApi.payOrder(row.orderNo);
    if (response.success) {
      ElMessage.success(t('order.paySuccess'));
      await loadOrderData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || t('order.payFailed'));
    }
  } catch (error) {
    console.error('支付订单失败:', error);
    ElMessage.error(t('order.payFailedRetry'));
  }
};

// 退款订单
const handleRefund = async (row) => {
  try {
    const response = await orderApi.refundOrder(row.orderNo);
    if (response.success) {
      ElMessage.success(t('order.refundSuccess'));
      await loadOrderData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || t('order.refundFailed'));
    }
  } catch (error) {
    console.error('退款订单失败:', error);
    ElMessage.error(t('order.refundFailedRetry'));
  }
};

// 页面挂载时加载数据
onMounted(() => {
  loadOrderData();
});

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
  loadOrderData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadOrderData();
};

// 使用 script setup 语法，无需 return
</script>

<style scoped src="@/styles/OrderManage.scss"></style>
